package com.mdd.controller;

import com.mdd.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载的处理
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 得到用户访问量
     * @return
     */
    @GetMapping("/uv")
    public R<Long> getUv(){
        HyperLogLogOperations<String, String> logLogOperations = redisTemplate.opsForHyperLogLog();
        return R.success(logLogOperations.size("UV:"));
    }

    @Value("${reggie.uploadpath}")
    private String uploadPath;

    /**
     * 处理文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();

        //判断当前目录是否存在
        File file1 = new File(uploadPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //获得文件类型
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用随机的uuid为上传的文件赋新文件名以防文件重名导致覆盖
        String fileName = UUID.randomUUID().toString()+suffix;
        file.transferTo(new File(uploadPath+fileName));
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void downFile(String name, HttpServletResponse response) throws IOException {
        //下载的文件
        File file = new File(uploadPath + name);
        //输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //设置响应数据的类型
        response.setContentType("image/jpeg");
        byte[] bytes = new byte[1024];
        int len =0;
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //边读边写
        while ((len = fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        //关闭流
        outputStream.close();
        fileInputStream.close();
    }

}
